package com.lightningtrade.web.core.config;
import com.lightningtrade.security.filter.JwtAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import javax.servlet.http.HttpServletResponse;

@Configuration
//@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter { //继承SpringSecurity 提供的 WebSecurityConfigurerAdapter


    // 注入 JWT 过滤器
    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;


    //创建BCryptPasswordEncoder注入容器
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                // 关闭 CSRF
                .csrf().disable()
                //跨域访问
                .cors().and()
                // 禁用 session获取SecurityContext, 用来存储用户登录的认证信息，入门案例所使用的方法
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 公共接口
                .antMatchers("/register", "/login","/product/getProductById/**", "/carousel/list","/product/list","/product/getProductByName/**").permitAll()  // These endpoints don't require token
                .antMatchers(HttpMethod.GET, "/", "/*.html", "/**/*.html", "/**/*.css", "/**/*.js", "/profile/**").permitAll()
                .antMatchers("/swagger-ui.html", "/swagger-resources/**", "/webjars/**", "/*/api-docs", "/druid/**").permitAll()

                // 基于角色的权限 可以用注解@PreAuthorize("hasRole('ROLE_ADMIN')")代替

                // .antMatchers("/admin/**").hasRole("ADMIN") // 只有 ADMIN 角色可以访问
                //.antMatchers("/seller/**").hasRole("SELLER") // 只有 SELLER 角色可以访问
                //.antMatchers("/user/**").hasRole("USER") // 只有 USER 角色可以访问

                .anyRequest().authenticated()
                .and()  // 其他请求都需要认证
                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);  // 将 JWT 过滤器添加到过滤链中，并确保其在 UsernamePasswordAuthenticationFilter 之前执行

        http.logout().disable(); // 禁用退出登录
        http.formLogin().disable(); // 禁用表单登录
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOriginPattern("*"); // 允许所有域名
        config.addAllowedHeader("*"); // 允许所有请求头
        config.addAllowedMethod("*"); // 允许所有方法（GET、POST 等）
        config.setAllowCredentials(true); // 允许发送 Cookie
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}